/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.consumer.modular.structure.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.consumer.core.enums.ConsumerBuildInEnum;
import vip.xiaonuo.consumer.core.enums.ConsumerDataTypeEnum;
import vip.xiaonuo.consumer.modular.structure.org.entity.ConsumerOrg;
import vip.xiaonuo.consumer.modular.structure.org.enums.ConsumerOrgCategoryEnum;
import vip.xiaonuo.consumer.modular.structure.org.mapper.ConsumerOrgMapper;
import vip.xiaonuo.consumer.modular.structure.org.param.*;
import vip.xiaonuo.consumer.modular.structure.org.service.ConsumerOrgService;
import vip.xiaonuo.consumer.modular.structure.position.entity.ConsumerPosition;
import vip.xiaonuo.consumer.modular.structure.position.service.ConsumerPositionService;
import vip.xiaonuo.consumer.modular.structure.user.entity.ConsumerUser;
import vip.xiaonuo.consumer.modular.structure.user.service.ConsumerUserService;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.sys.api.SysRoleApi;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 机构Service接口实现类
 *
 * @author xuyuxiang
 * @date 2022/2/23 18:43
 **/
@Service
public class ConsumerOrgServiceImpl extends ServiceImpl<ConsumerOrgMapper, ConsumerOrg> implements ConsumerOrgService {

    public static final String ORG_CACHE_ALL_KEY = "sys-org:all";

    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Resource
    private SysRoleApi sysRoleApi;

    @Resource
    private ConsumerPositionService consumerPositionService;

    @Resource
    private ConsumerUserService consumerUserService;

    @Override
    public Page<ConsumerOrg> page(ConsumerOrgPageParam consumerOrgPageParam) {
        QueryWrapper<ConsumerOrg> queryWrapper = new QueryWrapper<ConsumerOrg>().checkSqlInjection();
        // 查询部分字段
        queryWrapper.lambda().select(ConsumerOrg::getId, ConsumerOrg::getParentId, ConsumerOrg::getName,
                ConsumerOrg::getCategory, ConsumerOrg::getSortCode);
        if(ObjectUtil.isNotEmpty(consumerOrgPageParam.getParentId())) {
            queryWrapper.lambda().eq(ConsumerOrg::getParentId, consumerOrgPageParam.getParentId());
        }
        if(ObjectUtil.isNotEmpty(consumerOrgPageParam.getSearchKey())) {
            queryWrapper.lambda().like(ConsumerOrg::getName, consumerOrgPageParam.getSearchKey());
        }
        //数据归属
        queryWrapper.lambda().eq(ConsumerOrg::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(consumerOrgPageParam.getSortField(), consumerOrgPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(consumerOrgPageParam.getSortOrder());
            queryWrapper.orderBy(true, consumerOrgPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(consumerOrgPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ConsumerOrg::getSortCode);
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.lambda().in(ConsumerOrg::getId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<Tree<String>> tree() {
        // 获取本单位所有机构
        List<ConsumerOrg> allOrgList = this.list(new LambdaQueryWrapper<ConsumerOrg>().eq(ConsumerOrg::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()));
        // 定义机构集合
        Set<ConsumerOrg> consumerOrgSet = CollectionUtil.newHashSet();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            loginUserDataScope.forEach(orgId -> consumerOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
        } else {
            return CollectionUtil.newArrayList();
        }
        List<TreeNode<String>> treeNodeList = consumerOrgSet.stream().map(consumerOrg ->
                new TreeNode<>(consumerOrg.getId(), consumerOrg.getParentId(),
                        consumerOrg.getName(), consumerOrg.getSortCode()).setExtra(JSONUtil.parseObj(consumerOrg)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ConsumerOrgAddParam consumerOrgAddParam) {
        ConsumerOrgCategoryEnum.validate(consumerOrgAddParam.getCategory());
        //如果不是超管，校验数据范围，只能修改下级机构名称
        if(ObjectUtil.notEqual(StpLoginUserUtil.getLoginUser().getAccount(), ConsumerBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue())) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if (!loginUserDataScope.contains(consumerOrgAddParam.getParentId())) {
                    throw new CommonException("您没有权限在该机构下增加机构，机构id：{}", consumerOrgAddParam.getParentId());
                }
            } else {
                throw new CommonException("您没有权限增加机构");
            }
        }
        ConsumerOrg consumerOrg = BeanUtil.toBean(consumerOrgAddParam, ConsumerOrg.class);
        // 重复名称
        boolean repeatName = this.count(new LambdaQueryWrapper<ConsumerOrg>().eq(ConsumerOrg::getParentId, consumerOrg.getParentId())
                .eq(ConsumerOrg::getName, consumerOrg.getName())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级机构，名称为：{}", consumerOrg.getName());
        }
        //数据归属
        consumerOrg.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        consumerOrg.setCode(RandomUtil.randomString(10));
        this.save(consumerOrg);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(ConsumerDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(consumerOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ConsumerOrgEditParam consumerOrgEditParam) {
        ConsumerOrgCategoryEnum.validate(consumerOrgEditParam.getCategory());
        ConsumerOrg consumerOrg = this.queryEntity(consumerOrgEditParam.getId());
        //如果不是超管，校验数据范围，只能修改下级机构名称
        if(ObjectUtil.notEqual(StpLoginUserUtil.getLoginUser().getAccount(), ConsumerBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue())){
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.contains(consumerOrg.getId())) {
                    throw new CommonException("您没有权限编辑该机构，机构id：{}", consumerOrg.getId());
                }
                if(!loginUserDataScope.contains(consumerOrg.getParentId())) {
                    throw new CommonException("您没有权限编辑该机构下的机构，机构id：{}", consumerOrg.getParentId());
                }
            } else {
                throw new CommonException("您没有权限编辑该机构，机构id：{}", consumerOrg.getId());
            }
        }
        BeanUtil.copyProperties(consumerOrgEditParam, consumerOrg);
        boolean repeatName = this.count(new LambdaQueryWrapper<ConsumerOrg>().eq(ConsumerOrg::getParentId, consumerOrg.getParentId())
            .eq(ConsumerOrg::getName, consumerOrg.getName()).ne(ConsumerOrg::getId, consumerOrg.getId())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级机构，名称为：{}", consumerOrg.getName());
        }
        List<ConsumerOrg> originDataList = this.list();
        boolean errorLevel = this.getChildListById(originDataList, consumerOrg.getId(), true).stream()
            .map(ConsumerOrg::getId).collect(Collectors.toList()).contains(consumerOrg.getParentId());
        if(errorLevel) {
            throw new CommonException("不可选择上级机构：{}", this.getById(originDataList, consumerOrg.getParentId()).getName());
        }
        this.updateById(consumerOrg);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(ConsumerDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(consumerOrg));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ConsumerOrgIdParam> consumerOrgIdParamList) {
        List<String> orgIdList = CollStreamUtil.toList(consumerOrgIdParamList, ConsumerOrgIdParam::getId);
        if(ObjectUtil.isNotEmpty(orgIdList)) {
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(orgIdList)) {
                    throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
                }
            } else {
                throw new CommonException("您没有权限删除这些机构，机构id：{}", orgIdList);
            }
            List<ConsumerOrg> allOrgList = this.list();
            // 获取所有子机构
            List<String> toDeleteOrgIdList = CollectionUtil.newArrayList();
            orgIdList.forEach(orgId -> toDeleteOrgIdList.addAll(this.getChildListById(allOrgList, orgId, true).stream()
                    .map(ConsumerOrg::getId).collect(Collectors.toList())));
            // 机构下有人不能删除（直属机构）
            boolean hasOrgUser = consumerUserService.count(new LambdaQueryWrapper<ConsumerUser>().in(ConsumerUser::getOrgId, toDeleteOrgIdList)) > 0;
            if(hasOrgUser) {
                throw new CommonException("请先删除机构下的人员");
            }
            // 机构下有人不能删除（兼任机构）
            List<String> positionJsonList = consumerUserService.list(new LambdaQueryWrapper<ConsumerUser>()
                    .isNotNull(ConsumerUser::getPositionJson)).stream().map(ConsumerUser::getPositionJson).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(positionJsonList)) {
                List<String> positionOrgIdList = CollectionUtil.newArrayList();
                positionJsonList.forEach(positionJson -> JSONUtil.toList(JSONUtil.parseArray(positionJson), JSONObject.class)
                        .forEach(jsonObject -> positionOrgIdList.add(jsonObject.getStr("orgId"))));
                boolean hasPositionUser = CollectionUtil.intersectionDistinct(toDeleteOrgIdList, CollectionUtil.removeNull(positionOrgIdList)).size() > 0;
                if(hasPositionUser) {
                    throw new CommonException("请先删除机构下的人员");
                }
            }
            // 机构下有角色不能删除
            boolean hasRole = sysRoleApi.orgHasRole(toDeleteOrgIdList);
            if(hasRole) {
                throw new CommonException("请先删除机构下的角色");
            }
            // 机构下有岗位不能删除
            boolean hasPosition = consumerPositionService.count(new LambdaQueryWrapper<ConsumerPosition>().in(ConsumerPosition::getOrgId, toDeleteOrgIdList)) > 0;
            if(hasPosition) {
                throw new CommonException("请先删除机构下的岗位");
            }
            // 执行删除
            this.removeByIds(toDeleteOrgIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(ConsumerDataTypeEnum.ORG.getValue(), toDeleteOrgIdList);
        }
    }

    @Override
    public ConsumerOrg detail(ConsumerOrgIdParam consumerOrgIdParam) {
        return this.queryEntity(consumerOrgIdParam.getId());
    }

    @Override
    public ConsumerOrg queryEntity(String id) {
        ConsumerOrg consumerOrg = this.getById(id);
        if(ObjectUtil.isEmpty(consumerOrg)) {
            throw new CommonException("机构不存在，id值为：{}", id);
        }
        return consumerOrg;
    }

    @Override
    public List<ConsumerOrg> getAllOrgList(String companyId) {
        return this.list(new LambdaQueryWrapper<ConsumerOrg>().eq(ConsumerOrg::getCompanyId,companyId).orderByAsc(ConsumerOrg::getSortCode));
    }

    @Override
    public String getOrgIdByOrgFullNameWithCreate(String orgFullName) {
        List<ConsumerOrg> cachedAllOrgList = this.getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId());
        List<Tree<String>> treeList = TreeUtil.build(cachedAllOrgList.stream().map(consumerOrg ->
                new TreeNode<>(consumerOrg.getId(), consumerOrg.getParentId(), consumerOrg.getName(), consumerOrg.getSortCode()))
                .collect(Collectors.toList()), "0");
        return findOrgIdByOrgName("0", StrUtil.split(orgFullName, StrUtil.DASHED).iterator(), cachedAllOrgList, treeList);
    }

    public String findOrgIdByOrgName(String parentId, Iterator<String> iterator, List<ConsumerOrg> cachedAllOrgList, List<Tree<String>> treeList) {
        String orgName = iterator.next();
        if(ObjectUtil.isNotEmpty(treeList)) {
            List<Tree<String>> findList = treeList.stream().filter(tree -> tree.getName().equals(orgName)).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(findList)) {
                if(iterator.hasNext()) {
                    return findOrgIdByOrgName(findList.get(0).getId(), iterator, cachedAllOrgList, findList.get(0).getChildren());
                } else {
                    return findList.get(0).getId();
                }
            }
        }
        String orgId = this.doCreateOrg(parentId, orgName, cachedAllOrgList);
        if(iterator.hasNext()) {
            return findOrgIdByOrgName(orgId, iterator, cachedAllOrgList, CollectionUtil.newArrayList());
        } else {
            return orgId;
        }
    }

    /**
     * 执行创建机构
     *
     * @author xuyuxiang
     * @date 2023/3/8 9:38
     **/
    public String doCreateOrg(String parentId, String orgName, List<ConsumerOrg> cachedAllOrgList) {
        //创建该机构
        ConsumerOrg consumerOrg = new ConsumerOrg();
        consumerOrg.setName(orgName);
        consumerOrg.setCode(RandomUtil.randomString(10));
        consumerOrg.setParentId(parentId);
        consumerOrg.setCategory("0".equals(parentId)?ConsumerOrgCategoryEnum.COMPANY.getValue():ConsumerOrgCategoryEnum.DEPT.getValue());
        consumerOrg.setSortCode(99);
        this.save(consumerOrg);
        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(ConsumerDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(consumerOrg));
        // 将该机构加入缓存
        cachedAllOrgList.add(consumerOrg);
        // 更新缓存
        commonCacheOperator.put(ORG_CACHE_ALL_KEY, cachedAllOrgList);
        return consumerOrg.getId();
    }

    /* ====机构部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<ConsumerOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //Mr.wu 2024-9-20改为显示本单位全部机构
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {loginUserDataScope.addAll(dataScope.getDataScope());}));
        // 定义机构集合
        Set<ConsumerOrg> consumerOrgSet = CollectionUtil.newHashSet();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<ConsumerOrg> allOrgList = this.list();
            loginUserDataScope.forEach(orgId -> consumerOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = consumerOrgSet.stream().map(ConsumerOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(ConsumerOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(ConsumerOrg::getSortCode);
        List<ConsumerOrg> consumerOrgList = this.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = consumerOrgList.stream().map(consumerOrg ->
                        new TreeNode<>(consumerOrg.getId(), consumerOrg.getParentId(), consumerOrg.getName(), consumerOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public List<ConsumerOrg> orgListSelector(ConsumerOrgSelectorOrgListParam consumerOrgSelectorOrgListParam) {
        LambdaQueryWrapper<ConsumerOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //Mr.wu 2024-9-20改为显示本单位全部机构
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {loginUserDataScope.addAll(dataScope.getDataScope());}));
        // 定义机构集合
        Set<ConsumerOrg> consumerOrgSet = CollectionUtil.newHashSet();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<ConsumerOrg> allOrgList = this.list();
            loginUserDataScope.forEach(orgId -> consumerOrgSet.addAll(this.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = consumerOrgSet.stream().map(ConsumerOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(ConsumerOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(ConsumerOrg::getSortCode);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public Page<ConsumerUser> userSelector(ConsumerOrgSelectorUserParam consumerOrgSelectorUserParam) {
        LambdaQueryWrapper<ConsumerUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {loginUserDataScope.addAll(dataScope.getDataScope());}));
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(ConsumerUser::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 只查询部分字段
        lambdaQueryWrapper.select(ConsumerUser::getId, ConsumerUser::getAvatar, ConsumerUser::getOrgId, ConsumerUser::getPositionId, ConsumerUser::getAccount,
                ConsumerUser::getName, ConsumerUser::getSortCode, ConsumerUser::getGender, ConsumerUser::getEntryDate);

        if (ObjectUtil.isNotEmpty(consumerOrgSelectorUserParam.getOrgId())) {
            // 如果机构id不为空，则查询该机构及其子机构下的所有人
            List<String> childOrgIdList = CollStreamUtil.toList(this.getChildListById(this
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), consumerOrgSelectorUserParam.getOrgId(), true), ConsumerOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                lambdaQueryWrapper.in(ConsumerUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
        }
        //排除超管
        lambdaQueryWrapper.ne(ConsumerUser::getAccount, ConsumerBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());

        if(ObjectUtil.isNotEmpty(consumerOrgSelectorUserParam.getSearchKey())) {
            lambdaQueryWrapper.like(ConsumerUser::getName, consumerOrgSelectorUserParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(ConsumerUser::getSortCode);
        return consumerUserService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    /* ====以下为各种递归方法==== */

    @Override
    public List<ConsumerOrg> getParentAndChildListById(List<ConsumerOrg> originDataList, String id, boolean includeSelf) {
        List<ConsumerOrg> parentListById = this.getParentListById(originDataList, id, false);
        List<ConsumerOrg> childListById = this.getChildListById(originDataList, id, true);
        parentListById.addAll(childListById);
        return parentListById;
    }

    public List<ConsumerOrg> getChildListById(List<ConsumerOrg> originDataList, String id, boolean includeSelf) {
        List<ConsumerOrg> resultList = CollectionUtil.newArrayList();
        execRecursionFindChild(originDataList, id, resultList);
        if(includeSelf) {
            ConsumerOrg self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    @Override
    public List<ConsumerOrg> getParentListById(List<ConsumerOrg> originDataList, String id, boolean includeSelf) {
        List<ConsumerOrg> resultList = CollectionUtil.newArrayList();
        execRecursionFindParent(originDataList, id, resultList);
        if(includeSelf) {
            ConsumerOrg self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }


    public void execRecursionFindChild(List<ConsumerOrg> originDataList, String id, List<ConsumerOrg> resultList) {
        originDataList.forEach(item -> {
            if(item.getParentId().equals(id)) {
                resultList.add(item);
                execRecursionFindChild(originDataList, item.getId(), resultList);
            }
        });
    }

    public void execRecursionFindParent(List<ConsumerOrg> originDataList, String id, List<ConsumerOrg> resultList) {
        originDataList.forEach(item -> {
            if(item.getId().equals(id)) {
                ConsumerOrg parent = this.getById(originDataList, item.getParentId());
                if(ObjectUtil.isNotEmpty(parent)) {
                    resultList.add(parent);
                }
                execRecursionFindParent(originDataList, item.getParentId(), resultList);
            }
        });
    }

    @Override
    public ConsumerOrg getById(List<ConsumerOrg> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, ConsumerOrg::getId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }

    @Override
    public ConsumerOrg getParentById(List<ConsumerOrg> originDataList, String id) {
        ConsumerOrg self = this.getById(originDataList, id);
        return ObjectUtil.isNotEmpty(self)?self:this.getById(originDataList, self.getParentId());
    }

    @Override
    public ConsumerOrg getChildById(List<ConsumerOrg> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, ConsumerOrg::getParentId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }
}
